using System;
using UnityEngine;
using System.Collections;

public class PlanBuildAStarPath : Plan
{

	private pathplanner pathPlanner;
	private bool pathFound = false;
	
	private float nextSearchTime;
	private float searchInterval = 0.05f ; //Seconds
	
	private int nodesPerCycle; // number of nodes to open per frame
	
	private int nodesDone = 0;	
	
	private GameController gameController;
	
	public PlanBuildAStarPath (Vector3 position, Maze maze, Vector3 destination, int maxNodes, ArrayList obstacles)
	{
		gameController = (GameController)GameObject. FindWithTag("GameController").GetComponent("GameController");
		pathPlanner = new pathplanner(position, destination, maze, null, obstacles, maxNodes);	
		nextSearchTime = Time.timeSinceLevelLoad + searchInterval + UnityEngine.Random.value * 0.01f;
	}	
	
	public override bool execute ()
	{
		if (!pathFound)
		{
			if (Time.timeSinceLevelLoad > nextSearchTime)
			{
				nodesPerCycle = (int)(50.0f * (9.0f*gameController.getAStarCPUUsage()+1.0f));
				if (nodesDone > 1000)
					nodesPerCycle -= 5;
				if (nodesDone > 1400)
					nodesPerCycle -= 5;
				if (nodesDone > 1700)
					nodesPerCycle -= 5;
					
				if (nodesPerCycle < 5)
					nodesPerCycle = 5;
				pathFound = pathPlanner.find_path(nodesPerCycle);
				nodesDone += nodesPerCycle;
				nextSearchTime = Time.timeSinceLevelLoad + searchInterval + UnityEngine.Random.value * 0.01f;
			}
			return true;	// Keep searching for path
		}else
		{
			return false; // Path complete 
		}
	}

	public override pathplanner getPathPlanner ()
	{
		return pathPlanner;
	}

	public override string ToString ()
	{
		string returnString = string.Format ("A*( ");
		if (!pathFound)
			returnString += "searching... " + nodesDone + " nodes";
		returnString += " )";
		return returnString;
	}
	
	
	
	
	
}

